-module(sub_dict).
-behaviour(gen_server).
-define(SERVER,?MODULE).

-export([start/0,start_link/0,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).
-export([do/2]).

do(create,{Address_Type,Address,Pid}) ->
	gen_server:call(?SERVER,{add,Address_Type,Address,Pid});
do(get,{Address_Type,Address}) ->
	gen_server:call(?SERVER,{get,Address_Type,Address}).

start()  ->
	gen_server:start({local, ?SERVER}, ?MODULE, [], []).
start_link() ->
	gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
init(_) ->
	io:format("~s start...~n",[?SERVER]),
	{ok,{running,{dict:new(),dict:new()}}}.
	
handle_call({get,ip,IP},_,{running,{Mac_Dict,IP_Dict}}) ->
	{reply,retrive_sub(IP,IP_Dict),{running,{Mac_Dict,IP_Dict}}};

handle_call({get,mac,Mac},_,{running,{Mac_Dict,IP_Dict}}) ->
	{reply,retrive_sub(Mac,Mac_Dict),{running,{Mac_Dict,IP_Dict}}};

handle_call({add,mac,Mac,Pid},_,{running,{Mac_Dict,IP_Dict}}) ->
	{ok,New_Mac_Dict} = add_sub(Mac,Pid,Mac_Dict),
	{reply,ok,{running,{New_Mac_Dict,IP_Dict}}};
	
handle_call({add,ip,IP,Pid},_,{running,{Mac_Dict,IP_Dict}}) ->
	{ok,New_IP_Dict} = add_sub(IP,Pid,IP_Dict),
	{reply,ok,{running,{Mac_Dict,New_IP_Dict}}};
handle_call(Req,_,State) ->
	io:format("wrong request ~p ~n",[Req]),
	{reply, {error,"no func define"}, State}.
	
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.
	
retrive_sub(Key,Dict) ->
	try
		dict:fetch(Key,Dict)
	of
		Val -> Val
	catch
		_:_ ->
			unknown
	end.
add_sub(Key,Value,Dict) ->
	{ok,dict:store(Key, Value, Dict)}.
	